﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using BingVis.SilverlightClient.Common;
using Microsoft.VirtualEarth.MapControl;
using Microsoft.VirtualEarth.MapControl.Design;

namespace BingVis.SilverlightClient
{
    

    public partial class MainPage : UserControl
    {
        private MainShellViewModel model = new MainShellViewModel();

        private CompressFileWindow cfw;

        public MainPage()
        {
            InitializeComponent();

            this.DataContext = model;
            this.cfw = new CompressFileWindow(model);

            AppMediator.Instance.Register<StopSelectedMessage>(this, x => OnStopSelected(x.Content));

            GoToDefaultMap();
        }

        private void GoToDefaultMap()
        {
            Map.View = GetMapSpec(model.StartupLatLong, 10);
        }

        private MapViewSpecificationConverter cvt = new MapViewSpecificationConverter();
        private void OnStopSelected(ITransitStop stop)
        {
            Map.View = GetMapSpec(stop);
        }

        private MapViewSpecification GetMapSpec(ILocation loc)
        { return GetMapSpec(loc, 16); }
    
        private MapViewSpecification GetMapSpec(ILocation loc, int zoomLevel)
        {
            return (MapViewSpecification)cvt.ConvertFromString(String.Format("{0},{1},0.0000 {2:0.0000} 0.0000", loc.Latitude, loc.Longitude, zoomLevel));
        }

        private void TextBox_KeyUp(object sender, KeyEventArgs e)
        {
            // Manually trigger the binding... 
            txtFilter.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            model.StopsFilter = txtFilter.Text;

            // Pass through to model...  I'm lazy and don't want to re-write the behavior for silverlight.
            model.FilterOnEnter.Execute(e);
        }

        private void Install_Click(object sender, RoutedEventArgs e)
        {
            if (Application.Current.InstallState != InstallState.Installed)
            {
                var result = false;
                try
                {
                    result = Application.Current.Install();
                }
                catch
                {
                    MessageBox.Show("Aw snap... There was a problem installing. Sorry.");
                }
            }
            else
                MessageBox.Show("You appear to have already installed this application.");
        }

        private void CompressButton_Click(object sender, RoutedEventArgs e)
        {
            this.cfw.Show();
        }
    }
}
